﻿#ifndef MEMSDATACODEC_H
#define MEMSDATACODEC_H

#include <qobject.h>
#include <qbytearray.h>

class SerialPortManager;
class LogSaver;

class MEMSDataCodec : public QObject
{
  Q_OBJECT

public:
  enum DataFlag {
    Head = 0xaa,//头部
    SingleData = 0xcc,//单个数据
    MultiData1 = 0xb1,//组数据1
    MultiData2 = 0xb2,//组数据2
    MultiData3 = 0xb3,//组数据3
    MultiData4 = 0xb4,//组数据4
    MultiData5 = 0xb5,//组数据5
    MultiData6 = 0xb6,//组数据6
  };
  enum DataPackagetype
  {
    Single,
    Multi
  };
private:
  QByteArray dataBuffer;//数据缓冲区
  int dataPackageSize = 17;//数据包长度，单位：字节
  DataPackagetype dataPackagetype = Single;

  SerialPortManager* serialPortManager = Q_NULLPTR;//使用的串口管理器
  LogSaver* logSaver = Q_NULLPTR;
public:
  MEMSDataCodec(QObject* parent = Q_NULLPTR);
  ~MEMSDataCodec();

signals:
  void signal_sendData(QByteArray data);//发送数据到串口
  void signal_feedbackData(int dataGroupIndex, QByteArray data);//发送拆解后的反馈的数据
  void signal_currentDataPackageype(DataPackagetype dataPackagetype);

public slots:
  void slot_decode(QByteArray data);
  //代码优化，模块化
private:
  void decode();
  bool checkDataPackageHead();
  bool checkDataPackageGroupFlag();
  bool checkDataPackageGroupFlag(int* dataPackageType, int* groupIndex);
  bool checkDataPackageCheckSummation(int dataPackageType);
  void dataBufferDropData(int byteCount);
  void addCheckSummation(QByteArray* instruction);
  short char2ToShort(char H8, char L8);
  char* shortToChar2(short data, char* data1);
  bool checkCheckSummation(int begin, int end);

  char bitSum(char x, char y);
  //geter and seter
public:
  LogSaver* getLogSaver();
  void setLogSaver(LogSaver* logSaver);
  SerialPortManager* getSerialPortManager();
  void setSerialPortManager(SerialPortManager* serialPortManager);
  DataPackagetype getDataPackagetype();
  void setDataPackagetype(DataPackagetype dataPackagetype);
};
#endif
